<?php
// Copyright 2008 Datapolis Solutions OY
// 
// This file is part of a program, that is distributed
// under the terms of the GNU General Public License,
// see license.txt for details.


class DPHTTPClient {
	
	function DPHTTPClient ( )
	{
		
	}
	
	/**
	* array
	* (
	*	'header' => <http header>,
	*	'data' => <http data>
	* )
	* 
	* @param  string  $server  server name
	* @param  int     $port    port number
	* @param  string  $uri     target file on $server
	* @param  array   $request (optional) array of parameters, array('page' => 1, 'limit' => 5)
	* @param  array   $auth    (optional) array of authorization parameters, array('user' => 'foo', 'pw' => 'bar')
	* @return array or false on error
	*/
	function &httpGet ( $server, $port, $uri, $request=null, $auth=null )
	{
		$falseReturn = false;
		$server_ip = gethostbyname($server);
		$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
		if ($socket < 0) {
			return $falseReturn;
		}
		
		$result = socket_connect($socket, $server_ip, $port);
		if ($result < 0) {
			return $falseReturn;
		}
		
		$data="";
		if( is_array($request) ){
			if( count($request) > 0 ){
				foreach( $request as $rkey => $rval ){
					$data .= $rkey."=".urlencode($rval)."&";
				}
				if( !empty($data) ){
					$data = substr($data, 0, -1);
				}
			}
		}
		
		$authData="";
		if( is_array($auth) ){
			if( isset($auth['user']) && isset($auth['pw']) ){
				$authData="Authorization: Basic ".base64_encode($auth['user'].":".$auth['pw'])."\r\n";
			}
		}
		
		$in = "GET ".$uri.($data != "" ? "?$data" : "")." HTTP/1.0\r\n"
			."Host: ".$server."\r\n"
			.($authData != "" ? $authData : "")
			."Connection: Close\r\n"
			."Content-type: text/xml; charset=ISO-8859-1\r\n"
			."\r\n";
		
		$swrite = socket_write($socket, $in, strlen($in));
		if( $swrite === false ){
			return $falseReturn;
		}
		
		$data_out = '';
		while ($responsebuff = socket_read($socket, 2048)) {
			$data_out .= $responsebuff;
		}
		
		socket_close($socket);
		
		$http_header_delim = "\r\n\r\n";
		$http_header_pos = strpos($data_out, $http_header_delim);
		$http_header = substr($data_out, 0, $http_header_pos);
		$http_data = substr($data_out, ($http_header_pos+strlen($http_header_delim)));
		
		$ret = array('header' => $http_header, 'data' => $http_data);
		return $ret;
	}
}

?>